package com.monolithiot.sso.common.util;

import java.util.*;
import java.util.function.Function;

/**
 * 2018/12/3 Create by 郭文梁
 * CollectionUtil
 * 集合工具类
 *
 * @author 郭文梁
 * @date 2018/12/3
 */
public class CollectionUtil {
    /**
     * 默认MAP初始化大小
     */
    private static final int DEFAULT_MAP_INITIAL_CAPACITY = 10;

    /**
     * 分拣存储
     *
     * @param source 源集合
     * @param keyFun key生成策略
     * @param <S>    源类型
     * @param <K>    key类型
     * @return {key:[valueList]}
     */
    public static <S, K> Map<K, List<S>> sorting(Collection<S> source, Function<S, K> keyFun) {
        Map<K, List<S>> result = new HashMap<>(DEFAULT_MAP_INITIAL_CAPACITY);
        for (S o : source) {
            K key = keyFun.apply(o);
            List<S> itemList = result.computeIfAbsent(key, k -> new ArrayList<>());
            itemList.add(o);
        }
        return result;
    }
}
